﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace TrailImage
{
    public partial class AuthForm : Form
	{
		FlickrNet.OAuthRequestToken _requestToken = null;

        public AuthForm() { InitializeComponent(); }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			// http://flickrnet.codeplex.com/discussions/276628
			FlickrNet.OAuthAccessToken accessToken = null;

			while (!e.Cancel)
			{
				try
				{
					accessToken = FlickrPlugin.Flickr.OAuthGetAccessToken(_requestToken, AuthorizationCode.Text);

					if (accessToken == null)
					{
						// keep trying
						Thread.Sleep(2000);
					}
					else
					{
						// persist token
						FlickrPlugin.Flickr.SetAccessToken(accessToken);
						break;
					}
				}
				catch (FlickrNet.FlickrApiException ex)
				{
					if (ex.Code == 108) { }
				}
			}
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
            if (!e.Cancelled) { base.DialogResult = DialogResult.OK; }
        }

        private void HandleAuthorizeButtonClick(object sender, EventArgs e)
		{
			AuthorizeButton.Visible = false;
			FinishButton.Visible = true;
			AuthorizationLabel.Enabled = true;
			AuthorizationCode.Enabled = true;

			_requestToken = FlickrPlugin.Flickr.OAuthGetRequestToken("oob");
			string url = FlickrPlugin.Flickr.OAuthCalculateAuthorizationUrl(_requestToken.Token, FlickrNet.AuthLevel.Read);
			System.Diagnostics.Process.Start(url);
        }

		private void HandleCancelButtonClick(object sender, EventArgs e)
		{
			if (BackgroundWorker.IsBusy) { BackgroundWorker.CancelAsync(); }
			base.DialogResult = DialogResult.Cancel;
		}

		private void HandleFinishButtonClick(object sender, EventArgs e)
		{
			BackgroundWorker.RunWorkerAsync();
		}
    }
}